<?php

require_once './vendor/autoload.php';

// 请求地址  http://127.0.0.1?url=https://www.mikannovel.com&sleep=5&order=IP提取码
// http://www.data5u.com/?developer=76428d2f448ed36084ba2af8548789ae 注册账号后可以获得提取码

use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;

if (empty($_GET['url'])) {
    $result = ['message' => 'url必传', 'code' => 500];
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
    return;
}

$requestUrl = urldecode($_GET['url']);

$proxy = '';
if (isset($_GET['order']) && !empty($_GET['order'])) {
    $proxy = getProxyConfig($_GET['order']);
}

$sleepTime = $_GET['sleep'] ?? 10;
$timeout = $_GET['timeout'] ?? 10;
$ipAddress = getenv('WEBDRIVER') ?: '127.0.0.1';
$host = "http://{$ipAddress}:4444";

$chrome = DesiredCapabilities::chrome();

$oChromeOptions = new ChromeOptions();
$aArguments = [
    '--disable-gpu',
    '--no-sandbox',
    '--disable-dev-shm-usage',
    '--headless',
];
if ($proxy) {
    $aArguments[] = '--proxy-server=http://'.$proxy;
}

$oChromeOptions->addArguments($aArguments);

$chrome->setCapability(ChromeOptions::CAPABILITY, $oChromeOptions);
$driver = RemoteWebDriver::create($host, $chrome);

try {
    $driver->get($requestUrl);
    $driver->manage()->timeouts()->pageLoadTimeout((int) $timeout)->setScriptTimeout((int) $timeout);
    sleep(intval($sleepTime));
    $body = $driver->getPageSource();
    $result = ['message' => 'success', 'body' => $body, 'code' => 0, 'requestInfo' => ['url' => $requestUrl, 'proxy' => $proxy]];
} catch (\Exception $e) {
    $result = ['message' => $e->getMessage(), 'code' => 500, 'body' => '', 'requestInfo' => new stdClass()];
}

$driver->quit();

echo json_encode($result, JSON_UNESCAPED_UNICODE);

function getProxyConfig($order)
{
    $result = file_get_contents('http://api.ip.data5u.com/dynamic/get.html?order='.$order.'&sep=3&json=1');

    $resultArr = json_decode($result, true);
    if (is_null($resultArr)) {
        return '';
    }

    if (true === $resultArr['success'] && 'ok' == $resultArr['msg']) {
        $value = $resultArr['data'][0]['ip'].':'.$resultArr['data'][0]['port'];
    } else {
        $value = '';
    }

    return $value;
}
